package com.buba.controller;

import com.buba.pojo.Message;
import com.buba.pojo.UserInfo;
import com.buba.service.UserInfoService;
import com.buba.util.Pagination;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * @author 杨柳
 * @title UserInfoController
 * @date 2024/4/24 9:42
 */
@RestController
@CrossOrigin(allowCredentials = "true", originPatterns = "*")
public class UserInfoController {
    @Autowired
    private UserInfoService userInfoService;

    @GetMapping("/selUserInfoAll")
    public List<UserInfo> selUserInfoAll() {
        return userInfoService.selUserInfoAll();
    }

    @RequestMapping("/selUserInfo")
    public Pagination<UserInfo> selUserInfo(@RequestParam Map<String, Object> map) {
        Pagination<UserInfo> pagination = new Pagination<>();
        pagination.setPageNow(Long.parseLong(map.get("currentPage") + ""));
        pagination.setLimit(Long.parseLong(map.get("pageSize") + ""));
        map.put("index", pagination.getIndex());
        map.put("pageSize", pagination.getLimit());
        // 查询总条数
        pagination.setPageCount(userInfoService.selCount(map));
        // 计算总页数
        pagination.computePageTotal();
        // 查询当前页数据
        pagination.setList(userInfoService.selUserInfo(map));

        return pagination;
    }

    @RequestMapping("/delUserInfo")
    public Message delUserInfo(String userId) {
        long count = userInfoService.delUserInfo(userId);
        if (count == 0)
            return new Message(0, "删除失败");
        return new Message(1, "删除成功");
    }

    @RequestMapping("/addUserInfo")
    public Message addUserInfo(@RequestParam Map<String, Object> map) {
        long count = userInfoService.addUserInfo(map);
        if (count == 0)
            return new Message(0, "添加失败");
        return new Message(1, "添加成功");
    }

    @RequestMapping("/updUserInfo")
    public Message updUserInfo(@RequestParam Map<String, Object> map) {
        long count = userInfoService.updUserInfo(map);
        if (count == 0)
            return new Message(0, "修改失败");
        return new Message(1, "修改成功");
    }

    /**
     * 上传头像
     *
     * @param file
     * @return
     */
    @PostMapping("/upload")
    public String upload(MultipartFile file) {
        //原始文件名 1.jpg
        String originalFilename = file.getOriginalFilename();
        //获取原文件的类型 .jpg
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
        //使用UUID重新生成文件名，防止文件名称重复造成文件覆盖
        // UUID会生成一个永远不会重复的字符串
        String fileName = UUID.randomUUID() + suffix;
        //创建一个目录对象，用于存储上传文件
        File dir = new File("F:\\images\\");
        //判断当前目录是否存在：目录不存在，需要创建
        if (!dir.exists()) dir.mkdirs();
        try {
            //保存文件到指定目录
            file.transferTo(new File("F:\\images\\" + fileName));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return fileName;
    }

    /**
     * 下载图片
     *
     * @param name
     * @param response
     */
    @GetMapping("/download")
    public void download(String name, HttpServletResponse response) {
        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;
        if (name == null || name.equals("null") || name.equals("")) return;

        try {
            //输入流，通过输入流读取文件内容
            bis = new BufferedInputStream(new FileInputStream("F:\\images\\" + name));
            //输出流，通过输出流将文件写回浏览器
            bos = new BufferedOutputStream(response.getOutputStream());
            // 设置相应类型
            response.setContentType("image/png");
            int i = 0;
            while ((i = bis.read()) != -1) {
                bos.write(i);
            }
            bos.flush();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (bos != null) bos.close();
                if (bis != null) bis.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
